<template>
  <div class="df editor">
    <div class="preview-box xs-width-marging-0">
      <MdPreview :editorId="id" :modelValue="editContent" :theme="theme" />
      <declarant></declarant>
      <div class="df jc-c ai-c" :class="{ like: isLike }">
        <span class="icon iconfont icon-dianzan" @click="likeClick"></span>
        {{ article.like }}
      </div>
      <div class="comment_box mt20">
        评论：
        <comment :blogId="article.id"></comment>
      </div>
    </div>
    <div class="aside min-width-hide">
      <div class="catalog-box">
        <h3>目录</h3>
        <MdCatalog class="catalog" :editorId="id" :scrollElement="'main'" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref } from 'vue';
  import { storeToRefs } from 'pinia';
  import { MdPreview, MdCatalog } from 'md-editor-v3';
  import declarant from '@/components/declarant/declarant.vue';
  import { likeBlog } from '@/apis/article';
  import comment from '@/components/comment/comment.vue';
  import type { IBlog } from '@/apis/type';
  // preview.css相比style.css少了编辑器那部分样式
  import 'md-editor-v3/lib/preview.css';
  //   主题
  import { useThemeStore } from '@/stores/themeStore';
  let { theme } = storeToRefs(useThemeStore());

  const id = 'preview';
  // 内容 HTML
  let editContent = ref();
  // 文章信息
  let article = ref({} as IBlog);
  const props = defineProps({
    modelValue: {
      type: Object as PropType<IBlog>,
      default: () => {}
    }
  });
  watch(
    () => props.modelValue,
    val => {
      article.value = val;
      editContent.value = val.content;
    }
  );
  let isLike = ref(false);
  const likeClick = async () => {
    if (!isLike.value) {
      isLike.value = true;
      article.value.like++;
    } else {
      isLike.value = false;
      article.value.like--;
    }

    let title = '点赞成功，感谢您的喜欢';
    try {
      await likeBlog({ id: article.value.id, like: article.value.like });
      if (!isLike.value) title = '感谢您的阅读，如有不足，请留言';
      ElNotification({
        message: title,
        customClass: 'ElNotification',
        duration: 2000
      });
    } catch (err) {
      console.log('🚀 ~ err:', err);
    }
  };
</script>

<style scoped lang="scss">
  .editor {
    position: relative;
    width: 100%;
  }
  #preview {
    background-color: var(--bg-color);
  }
  .preview-box {
    margin-right: 20px;
    flex: 1;
    min-width: 0;
  }
  .aside {
    width: 300px;
  }
  .catalog-box {
    background-color: var(--bg-color);
    padding: 20px;
    position: sticky;
    top: 0;
  }
  .icon-dianzan {
    font-size: 25px;
    cursor: pointer;
    margin-right: 10px;
  }
  .like {
    color: var(--text-color-active);
  }
  .comment_box {
    background-color: var(--bg-color);
    padding: 20px;
  }
</style>
